//
//  RefreshToken.swift
//  APH
//
//  Created by Rdxer on 2017/12/8.
//  Copyright © 2017年 Rdxer. All rights reserved.
//

import Foundation
import RxSwift
import Moya
import Async


enum HTTPErrorCode:Int {
    case mapModelError = -90001
    case mapModelListError = -90002
    case serverResponseErr = -90003
}


// filterWhenNeedRefreshAoken
extension PrimitiveSequence where TraitType == SingleTrait, ElementType == Response {
    
    public func filterWhenNeedRefreshToken(target:AnyObject,sel:Selector) -> Single<ElementType> {
        
        return flatMap { [weak target] response -> Single<ElementType> in
            do {
                let e = try response.filterAllResponseDataError()
                return Single.just(e)
            } catch  {
                switch error {
                case let MoyaError.underlying(_Error, _):
                    if let _err = _Error as? NSError{
                        if _err.code == HTTPErrorCode.serverResponseErr.rawValue {
                            if let errCode = _err.userInfo["errCode"] as? Int, errCode == 1001{
                                ServerConfig.token = nil
                                if let t = target{
                                    HUD.dismiss()
                                    Async.main({
                                        HUD.dismiss()
                                    })
                                    Async.main(after: 0.001, {
                                        HUD.dismiss()
                                    })
                                    DispatchQueue.main
                                        .asyncAfter(deadline: DispatchTime.now()+0.1, execute: {
                                        t.performSelector(onMainThread: sel, with: nil, waitUntilDone: false)
                                    })
                                }
                            }
                        }
                    }
                default:
                    break
                }
                throw error
            }
        }
    }
    
    public func filterAllResponseDataError() -> Single<ElementType> {
        return flatMap { response -> Single<ElementType> in
            let e = try response.filterAllResponseDataError()
            return Single.just(e)
        }
    }
}


public extension Response {
    public func filterAllResponseDataError() throws -> Response {
        var jsonObject:Any? = nil
        do {
            jsonObject = try JSONSerialization.jsonObject(with:data, options: .allowFragments)
        } catch  {
            throw MoyaError.jsonMapping(self)
        }
        
        let jsonDict = jsonObject as? [String:Any]
        if let errCode = jsonDict?["errCode"] as? Int {
            if errCode != 0 {
                throw MoyaError.underlying(NSError.init(domain: "服务器返回数据异常", code: HTTPErrorCode.serverResponseErr.rawValue, userInfo: jsonDict), self)
            }
        }
        return self
    }
}
